package br.com.dallasmotopecas.util.converter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import org.apache.tomcat.util.codec.binary.Base64;

@FacesConverter(value="converterPickList")
public class ConverterPickList implements Converter
{

	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2)
	{
		byte[] data = null;
		ObjectInputStream inputStream = null;
		Object object = null;
		try 
		{
            //Teste de Ide
			data = Base64.decodeBase64(arg2);
            inputStream = new ObjectInputStream(new ByteArrayInputStream(data));
            object = inputStream.readObject();
            inputStream.close();
            return object;
        } 
		catch (Exception e) 
		{   
			e.printStackTrace();
        }
		return null;
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2)
	{
		ByteArrayOutputStream outputStream = null;
		ObjectOutputStream objectOutputStream = null;
		try 
		{
			outputStream = new ByteArrayOutputStream();
			objectOutputStream = new ObjectOutputStream(outputStream);
			objectOutputStream.writeObject(arg2);
			objectOutputStream.close();

            return Base64.encodeBase64String(outputStream.toByteArray());
        } 
		catch (IOException e) 
		{   
			e.printStackTrace();
        }
		return "";
	}

}
